package com.applink.sell_proof.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.WindowManager.BadTokenException;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.aplink.sell_proof.services.DataSync;
import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.NewLogInActivity;
import com.applink.sell_proof.R;
import com.applink.sell_proof.api.MethodParams;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.constant.StatusBGColor;
import com.applink.sell_proof.model.Country;
import com.applink.sell_proof.model.NewRewardClaim;
import com.applink.sell_proof.model.NewRewardClaimDetail;
import com.applink.sell_proof.model.NewRewardProject;
import com.applink.sell_proof.model.NewRewardProjectDetail;
import com.applink.sell_proof.model.ProductImage;
import com.applink.sell_proof.pojo.GenericAttribute;
import com.applink.sell_proof.pojo.GenericObject;
import com.applink.sell_proof.utilXMLParser.ObjPropInfo;

@SuppressLint("SimpleDateFormat")
public class Utility {
	public static ArrayList<ProductImage> mDataProductImage = new ArrayList<ProductImage>();
	public static ArrayList<NewRewardProject> mDataProject = new ArrayList<NewRewardProject>();
	public static ArrayList<NewRewardProjectDetail> mDataProjectDetails = new ArrayList<NewRewardProjectDetail>();
	public static ArrayList<NewRewardClaim> mDataClaim = new ArrayList<NewRewardClaim>();
	public static ArrayList<NewRewardClaimDetail> mDataClaimDetails = new ArrayList<NewRewardClaimDetail>();
	public static PopupWindow popupWindow;
	public static boolean checkLoadTip = false;
	public static boolean checkGetLastestPriceBook = false;
	public static boolean checkGetLastestPromotion = false;
	public static boolean checkGetLastestProduct = false;
	public static boolean checkPushQuiz = false;
	public static boolean checkQuiz = true;
	public static boolean checkTip = true;
	public static int countQuiz = 0;
	public static int countTip = 0;
	public static boolean checkLoadTipAgain = false;
	/**
	 * 
	 * 
	 * @param input
	 * @return
	 */
	public static String messageServerTimeOut = "Your working session is expired.\n Please open your internet to connect again.";
	public static String titleServerTimeOut = "Server session time out";
	public static String messageLocalTimeOut = "Your working session is expired. \n Please log in again.";
	public static String titleLocalTimeOut = "Log in session time out";
	public static boolean checkServerTimeOut = false;

	public static String formatValue(double value) {

		String strAfterFormat = new DecimalFormat("###,###,###").format(value);

		return "RM " + strAfterFormat;
	}

	public static String myURLencode(String input) {
		String output = input;

		output = output.replaceAll(" ", "%20");

		return output;
	}

	/**
	 * 
	 * 
	 * @param input
	 * @return
	 */
	public static String uRLfix(String input) {
		String output = input;

		output = output.replaceAll(" ", "_");

		return output;
	}

	public static Bitmap getBitmapFromUri(Context context, Uri uri)
			throws IOException, MalformedURLException {

		URL aURL = new URL(uri.toString());

		Options o = getBitmapOption(context, aURL);

		return BitmapFactory.decodeStream(aURL.openStream(), null, o);
	}

	public static Options getBitmapOption(Context context, URL url)
			throws IOException {

		int widthpixel = context.getResources().getDisplayMetrics().widthPixels;
		int heightpixel = context.getResources().getDisplayMetrics().heightPixels;

		Options o = new Options();

		// just decoding the boundary no actually image streaming
		o.inJustDecodeBounds = true;

		InputStream is = url.openStream();

		BitmapFactory.decodeStream(is, null, o);

		// get actual width x height of the image and calculate the scale
		// factor
		o.inSampleSize = countSampleValue(o.outWidth, o.outHeight, widthpixel,
				heightpixel);

		is.close();

		o.inJustDecodeBounds = false;

		return o;
	}

	/**
	 * 
	 * @param potentialDate
	 * @return
	 */
	public static Date findDate(String potentialDate) {

		DateFormat[] MANY_DATE_FORMATS = {
				new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"),
				new SimpleDateFormat("M/d/yyyy HH:mm:ss a"),
				new SimpleDateFormat("M/d/yyyy") };

		Date ret = null;

		FOUND: for (int i = 0; i < MANY_DATE_FORMATS.length; i++) {
			try {
				ret = MANY_DATE_FORMATS[i].parse(potentialDate);
				break FOUND;
			} catch (ParseException ignored) {
			}
		}

		return ret;
	}

	public static void initCountry(List<Country> countries, Spinner spinner,
			Activity currentAct) {
		if (countries != null) {
			ArrayAdapter<Country> adapter_country = new ArrayAdapter<Country>(
					currentAct, android.R.layout.simple_spinner_dropdown_item,
					countries);
			spinner.setAdapter(adapter_country);
		}
	}

	/**
	 * 
	 * get actual height of a ListView
	 * 
	 * @author Van Vu
	 * @param list
	 * @return
	 */
	public static int getListViewHeight(ListView list) {
		ListAdapter adapter = list.getAdapter();

		int listviewHeight = 0;

		list.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED,
				MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0,
				MeasureSpec.UNSPECIFIED));

		listviewHeight = list.getMeasuredHeight() * adapter.getCount()
				+ (adapter.getCount() * list.getDividerHeight());

		return listviewHeight;
	}

	/***
	 * 
	 * @param originalWidth
	 * @param originalHeight
	 * @param newWidth
	 * @param newHeight
	 * @return
	 */
	private static int countSampleValue(int originalWidth, int originalHeight,
			int newWidth, int newHeight) {
		int sample = 1;

		// prevent loop cycle in case our parameter is smaller than 0
		if (originalWidth <= 0 || originalHeight <= 0 || newWidth <= 0
				|| newHeight <= 0)
			return sample;

		while ((originalWidth >> 1 > newWidth)
				|| (originalHeight >> 1 > newHeight)) {

			sample <<= 1;
			originalWidth >>= 1;
			originalHeight >>= 1;

		}

		return sample;
	}

	/**
	 * Convert float to nice string
	 * 
	 * @param d
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public static String f2s(double d) {
		if (d == (int) d)
			return String.format("%d", (int) d);
		else
			return String.format("%s", d);
	}

	/**
	 * 
	 * Disable the edit/click on EditText or TextView
	 * 
	 * @param inputtype
	 * @param vg
	 */
	public static void disableTextView(int inputtype, ViewGroup vg) {

		for (int i = 0; i < vg.getChildCount(); i++) {
			View child = vg.getChildAt(i);

			if (child instanceof EditText) {
				((EditText) child).setInputType(inputtype);
			}

			child.setClickable(false);

			if (child instanceof ViewGroup) {
				disableTextView(inputtype, (ViewGroup) child);
			}
		}
	}

	public static void checkConnect(Context mContext) {
		// ConnectivityManager connect = (ConnectivityManager) mContext
		// .getSystemService(Context.CONNECTIVITY_SERVICE);
		// NetworkInfo infoWifi = connect
		// .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		// NetworkInfo infoMobile = connect
		// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		//
		// if (infoWifi.isConnected() || infoMobile.isConnected()) {
		// EMarketing.setOnline(true);
		// } else {
		// EMarketing.setOnline(false);
		// }
		ConnectivityManager cm = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			EMarketing.setOnline(true);
		} else {
			EMarketing.setOnline(false);
		}

	}

	/**
	 * 
	 * @param context
	 * @param icon
	 */
	public static void checkNetwork(Context context) {
		checkConnect(context);
		if (!EMarketing.isOnline()) {
			if (uDialog == null || !uDialog.isShowing()) {
				showDialogNetwork(context, android.R.drawable.ic_dialog_alert);
			}
		}
	}

	private static Dialog uDialog = null;

	public static void showDialogNetwork(final Context mContext, int icon) {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.textdialog, null);
		TextView textView = (TextView) layout.findViewById(R.id.txtDialog);
		textView.setText("No Internet Connection Available.Do you want to turn on the wifi?");
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle("Internet Connection");
		builder.setView(layout);
		builder.setCancelable(false);
		builder.setPositiveButton(R.string.yes,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(
								android.provider.Settings.ACTION_WIFI_SETTINGS);
						mContext.startActivity(intent);
						uDialog.dismiss();
						Constant.NETWORK_STATUS = true;
					}
				});

		builder.setNegativeButton(R.string.no,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						uDialog.dismiss();
						// Splash.getInstant.passToLogin();
						// Splash.getInstant.finish();
						Constant.NETWORK_STATUS = true;
					}
				});

		builder.setIcon(icon);
		try {
			uDialog = builder.create();
			uDialog.show();
		} catch (BadTokenException e) {
		}
	}

	public static void showAlertDialog(final Context mContext, int icon,
			String message, String title) {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.textdialog, null);
		TextView textView = (TextView) layout.findViewById(R.id.txtDialog);
		textView.setText(message);
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(title);
		builder.setView(layout);
		builder.setCancelable(false);
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Constant.countInvitation++;
					}
				});

		builder.setIcon(icon);
		try {
			uDialog = builder.create();
			uDialog.show();
		} catch (BadTokenException e) {
		}
	}

	public static boolean deleteFile(String url) {
		String path = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/SellProff/";
		String[] temp = url.split("/");
		String fileName = temp[temp.length - 1];
		path += fileName;
		File file = new File(path);
		return file.delete();
	}

	public static boolean isFileExists(String url) {
		String path = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/SellProff/";
		String[] temp = url.split("/");
		String fileName = temp[temp.length - 1];
		path += fileName;
		File file = new File(path);
		return file.exists();
	}

	public static String download(String urlImage) {
		try {
			URL url = new URL(urlImage);
			InputStream input = url.openStream();
			try {
				File storagePath = new File(
						Environment.getExternalStorageDirectory(), "SellProff");
				// System.out.println(">>> storagePath = " +
				// Environment.getDataDirectory());
				storagePath.mkdirs();
				// File storagePath = Environment.getExternalStorageDirectory();
				String temporaryName = String.format(Locale.getDefault(),
						"%d.jpg", System.currentTimeMillis());

				File pathURL = new File(storagePath, temporaryName);
				OutputStream output = new FileOutputStream(pathURL);

				try {
					byte[] buffer = new byte[1024];
					int bytesRead = 0;
					while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
						output.write(buffer, 0, bytesRead);
					}
					Log.v("nglehien",
							"downloaded: " + "file://" + pathURL.toString());
					return "file://" + pathURL.toString();
				} finally {
					output.close();
				}
			} finally {
				input.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @author Van Vu
	 * @param urlImage
	 * @param taskExcuteOnComplete
	 */
	public static void syncDownload(final String urlImage,
			final AsyncTask<String, ?, ?> taskExcuteOnComplete) {

		new AsyncTask<Void, Void, String>() {

			protected String doInBackground(Void... params) {

				try {
					URL url = new URL(urlImage);
					InputStream input = url.openStream();
					try {

						File storagePath = new File(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath(), "SellProff");

						storagePath.mkdirs();

						String temporaryName = String.format(
								Locale.getDefault(), "%d.jpg",
								System.currentTimeMillis());

						File pathURL = new File(storagePath, temporaryName);

						OutputStream output = new FileOutputStream(pathURL);

						System.out.println(">>>> path = " + pathURL.toString());
						try {
							byte[] buffer = new byte[1024];
							int bytesRead = 0;
							while ((bytesRead = input.read(buffer, 0,
									buffer.length)) >= 0) {
								output.write(buffer, 0, bytesRead);
							}

							return "file://" + pathURL.toString();
						} finally {
							output.close();
						}
					} finally {
						input.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(String filePath) {

				if (filePath != null)
					if (taskExcuteOnComplete != null)
						taskExcuteOnComplete.execute(filePath);
			}
		}.execute();
	}

	public static int getStatusBGColor(String status) {
		return StatusBGColor.Colors.get(status);
	}

	public static void SyncData() {
		// DataSync.doSync(new MethodParams(Methods.updateUserActivity));
		// DataSync.doSync(new MethodParams(Methods.projectsSync));
		DataSync.doSync(new MethodParams(Methods.searchProductModel));
		DataSync.doSync(new MethodParams(Methods.getAllDistributor));
	}

	public static void showWaitingStatus(ProgressDialog dialog) {
		try {
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
		dialog.setContentView(R.layout.progress_dialog);
		dialog.dismiss();
		dialog.show();
	}

	public static void showWaitingDialog(ProgressDialog dialog) {
		try {
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			dialog.setContentView(R.layout.progress_dialog_nomessages);
			dialog.dismiss();
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void hideWaitingStatus(ProgressDialog dialog) {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	@SuppressWarnings("rawtypes")
	public static ArrayList<GenericObject> convertProjectPojosIntoProjectGenericObjects(
			ArrayList<NewRewardProject> mDataProject2,
			ArrayList<ObjPropInfo> objPropList) {

		ArrayList<GenericObject> arrGenericObject = new ArrayList<GenericObject>();
		for (int i = 0; i < Utility.mDataProject.size(); i++) {
			NewRewardProject newRewardProject = Utility.mDataProject.get(i);

			ArrayList<GenericAttribute> arrAttributes = new ArrayList<GenericAttribute>();
			arrAttributes = newRewardProject
					.convertIntoGenericAttributes(objPropList);

			GenericObject genericObject = new GenericObject();
			// set Object name
			genericObject.setObjectName(objPropList.get(0).getOm());

			// set Attribute List
			genericObject.setAttributeList(arrAttributes);

			// add into genericObject List
			arrGenericObject.add(genericObject);
		}

		return arrGenericObject;
	}

	@SuppressWarnings("rawtypes")
	public static ArrayList<GenericObject> convertClaimPojosIntoClaimGenericObjects(
			ArrayList<NewRewardClaim> mDataProject2,
			ArrayList<ObjPropInfo> objPropList) {

		ArrayList<GenericObject> arrGenericObject = new ArrayList<GenericObject>();
		for (int i = 0; i < Utility.mDataClaim.size(); i++) {
			NewRewardClaim newRewardClaim = Utility.mDataClaim.get(i);

			ArrayList<GenericAttribute> arrAttributes = new ArrayList<GenericAttribute>();
			arrAttributes = newRewardClaim
					.convertIntoGenericAttributes(objPropList);
			GenericObject genericObject = new GenericObject();
			// set Object name
			genericObject.setObjectName(objPropList.get(0).getOm());

			// set Attribute List
			genericObject.setAttributeList(arrAttributes);

			// add into genericObject List
			arrGenericObject.add(genericObject);
		}

		return arrGenericObject;
	}

	@SuppressWarnings("rawtypes")
	public static ArrayList<GenericObject> convertProjectPojosIntoProjectGenericObjects(
			ArrayList<NewRewardProjectDetail> mDataProjectDetails2,
			int objectID, ArrayList<ObjPropInfo> objPropListDetail) {

		// filter by objectID
		ArrayList<NewRewardProjectDetail> mainArrRewardProjectDetailById = new ArrayList<NewRewardProjectDetail>();
		for (int i = 0; i < mDataProjectDetails2.size(); i++) {
			NewRewardProjectDetail newRewardProjectDetail = mDataProjectDetails2
					.get(i);
			if (newRewardProjectDetail.getObjectID().compareToIgnoreCase(
					String.valueOf(objectID)) == 0) {
				mainArrRewardProjectDetailById.add(newRewardProjectDetail);
			}
		}

		// we convert mainArrRewardProjectDetailById into GenericObjects
		ArrayList<GenericObject> arrGenericObject = new ArrayList<GenericObject>();
		for (int i = 0; i < mainArrRewardProjectDetailById.size(); i++) {
			NewRewardProjectDetail newRewardProjectDetail = mainArrRewardProjectDetailById
					.get(i);

			ArrayList<GenericAttribute> arrAttributes = new ArrayList<GenericAttribute>();
			arrAttributes = newRewardProjectDetail
					.convertIntoGenericAttributes(objPropListDetail);

			GenericObject genericObject = new GenericObject();
			// set Object name
			genericObject.setObjectName(objPropListDetail.get(0).getOm());

			// set Attribute List
			genericObject.setAttributeList(arrAttributes);

			// add into genericObject List
			arrGenericObject.add(genericObject);
		}

		return arrGenericObject;
	}

	@SuppressWarnings("rawtypes")
	public static ArrayList<GenericObject> convertClaimDetailPojosIntoClaimDetailGenericObjects(
			ArrayList<NewRewardClaimDetail> mDataProjectDetails2,
			int programID, int categoryID,
			ArrayList<ObjPropInfo> objPropListDetail) {

		// filter by objectID
		ArrayList<NewRewardClaimDetail> mainArrRewardProjectDetailById = new ArrayList<NewRewardClaimDetail>();
		for (int i = 0; i < mDataProjectDetails2.size(); i++) {
			NewRewardClaimDetail newRewardClaimDetail = mDataProjectDetails2
					.get(i);
			if (newRewardClaimDetail.getProgramID() == programID
					&& newRewardClaimDetail.getProductCategoryID() == categoryID) {
				mainArrRewardProjectDetailById.add(newRewardClaimDetail);
			}
		}

		// we convert mainArrRewardProjectDetailById into GenericObjects
		ArrayList<GenericObject> arrGenericObject = new ArrayList<GenericObject>();
		for (int i = 0; i < mainArrRewardProjectDetailById.size(); i++) {
			NewRewardClaimDetail newRewardProjectDetail = mainArrRewardProjectDetailById
					.get(i);

			ArrayList<GenericAttribute> arrAttributes = new ArrayList<GenericAttribute>();
			arrAttributes = newRewardProjectDetail
					.convertIntoGenericAttributes(objPropListDetail);

			GenericObject genericObject = new GenericObject();
			// set Object name
			genericObject.setObjectName(objPropListDetail.get(0).getOm());

			// set Attribute List
			genericObject.setAttributeList(arrAttributes);

			// add into genericObject List
			arrGenericObject.add(genericObject);
		}

		return arrGenericObject;
	}

	public static void checkExpireDay(String TokenExpiryDate)
			throws ParseException {
		int day = 0;
		int month = 0;
		int year = 0;
		String date = TokenExpiryDate;// jsonResult.getString("TokenExpiryDate");
		boolean leapYear = false;
		String[] elements = date.split("/");
		if (elements.length > 0) {
			day = Integer.parseInt(elements[0]);

			month = Integer.parseInt(elements[1]);

			year = Integer.parseInt(elements[2].toString().substring(0, 4)
					.toString());
		}

		String elementForTime = date.split(" ")[1];

		int hour = Integer.parseInt(elementForTime.split(":")[0]);
		int minute = Integer.parseInt(elementForTime.split(":")[1]);
		int second = Integer.parseInt(elementForTime.split(":")[2]);

		String timestampt = date.split(" ")[2];
		String pmTime = "pm";
		if (timestampt.toLowerCase().contains(pmTime) == true) {
			hour += 12;
		}
		if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
			leapYear = true;
		}
		if (hour == 0 && day == 1 && month == 1) {
			hour = 23;
			day = 31;
			month = 12;
			year--;
		} else if (hour == 0 && day == 1) {
			day = Integer.parseInt(previousDateString(String.valueOf(year)
					+ String.valueOf(month) + String.valueOf(day)));
			System.out.println("day = " + day);
			hour = 23;
			month--;
		} else if (hour == 0) {
			String monthFormat = "";
			String dayFormat = "";
			if (month < 10) {
				monthFormat = "0" + month;
			}
			if (day < 10) {
				dayFormat = "0" + day;
			}
			day = Integer.parseInt(previousDateString(String.valueOf(year)
					+ String.valueOf(monthFormat) + String.valueOf(dayFormat)));
			System.out.println("day = " + day);
			hour = 23;
		} else {
			hour--;
		}

		// we wrap TokenExpriedDate into Calendar variable
		Calendar tokenExpriedCal = Calendar.getInstance();

		tokenExpriedCal.set(Calendar.YEAR, year);
		tokenExpriedCal.set(Calendar.MONTH, month - 1); // since it runs from 0
														// index
		tokenExpriedCal.set(Calendar.DAY_OF_MONTH, day);
		tokenExpriedCal.set(Calendar.HOUR_OF_DAY, hour);
		tokenExpriedCal.set(Calendar.MINUTE, minute);
		tokenExpriedCal.set(Calendar.SECOND, second);

		// we get currentTime based on Calendar instance
		Calendar currentCal = Calendar.getInstance();
		int currentYear = currentCal.get(Calendar.YEAR);
		int currentMonth = currentCal.get(Calendar.MONTH) + 1;
		int currentDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int currentHourOfDay = currentCal.get(Calendar.HOUR_OF_DAY);
		int currentMinute = currentCal.get(Calendar.MINUTE);

		// add interval logout time for this currentLogin time

		currentCal.add(Calendar.MINUTE, NewLogInActivity.intervalTimeMinute);

		int newExpriedLocalYear = currentCal.get(Calendar.YEAR);
		int newExpriedLocalMonth = currentCal.get(Calendar.MONTH) + 1;
		int newExpriedLocalDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int newExpriedLocalHourOfDay = currentCal.get(Calendar.HOUR_OF_DAY);
		int newExpriedLocalMinute = currentCal.get(Calendar.MINUTE);

		// we compare this newExpriedLocalTime with TokenExpriedDate
		if (currentCal.compareTo(tokenExpriedCal) > 0) {
			// this expriedLocal is after expriedTokenDate
			// we assign again the expriedLocal by expriedTokenDate to make sure
			// it must always be earlier than tokenExpriedCal
			currentCal = tokenExpriedCal;

		} // otherwise, this newExpriedLocalDate is valid

		// we set currentCal as newLocalTimeOut in sharepreference
		long expiredServer = tokenExpriedCal.getTimeInMillis();
		long expiredLocal = currentCal.getTimeInMillis();

		EMarketing.getInstance()
				.setExpiredServer(String.valueOf(expiredServer));
		EMarketing.getInstance().setExpiredLocal(String.valueOf(expiredLocal));

	}

	private static String previousDateString(String dateString)
			throws ParseException {
		// Create a date formatter using your format string
		DateFormat dateFormat = new SimpleDateFormat("yyyymmdd");

		// Parse the given date string into a Date object.
		// Note: This can throw a ParseException.
		Date myDate = dateFormat.parse(dateString);

		// Use the Calendar class to subtract one day
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(myDate);
		calendar.add(Calendar.DAY_OF_YEAR, -1);

		// Use the date formatter to produce a formatted date string
		Date previousDate = calendar.getTime();
		String result = dateFormat.format(previousDate);

		return result;
	}

	public static int checkTimeValidation() {
		int isLoginState = 0;
		long currentCal = Calendar.getInstance().getTimeInMillis();
		long serverTimeout = Long.parseLong(EMarketing.getInstance()
				.getExpiredServer());
		long localTimeout = Long.parseLong(EMarketing.getInstance()
				.getExpiredLocal());
		if (currentCal > serverTimeout) {
			EMarketing.getInstance().setCheckLog(true);
			isLoginState = 0;
			EMarketing.getInstance().setExpiredLocal("");
			EMarketing.getInstance().setExpiredServer("");
			EMarketing.getInstance().setAccountPassword("");
		} else if (currentCal > localTimeout) {
			isLoginState = 1;
			EMarketing.getInstance().setExpiredLocal("");
		} else {
			isLoginState = 2;
		}
		return isLoginState;
	}

	public static void showAlertDialogLogout(final Context mContext, int icon,
			String message, String title, final Activity mActivity) {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.textdialog, null);
		TextView textView = (TextView) layout.findViewById(R.id.txtDialog);
		textView.setText(message);
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(title);
		builder.setView(layout);
		builder.setCancelable(false);
		builder.setPositiveButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						logout(mActivity);
					}
				});

		builder.setIcon(icon);
		try {
			AlertDialog uDialogLogout = builder.create();
			uDialogLogout.show();
		} catch (BadTokenException e) {
			e.printStackTrace();
		}
	}

	public static void logout(Activity mActivity) {
		EMarketing.getInstance().setLogin(false);
		Intent intent = new Intent(mActivity, NewLogInActivity.class);
		mActivity.finish();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TASK);
		mActivity.startActivity(intent);
	}

	public static void setLocalTimeExpiry() {

		// we get currentTime based on Calendar instance
		Calendar currentCal = Calendar.getInstance();

		// add interval logout time for this currentLogin time

		currentCal.add(Calendar.MINUTE, NewLogInActivity.intervalTimeMinute);

		long expiredLocal = currentCal.getTimeInMillis();

		EMarketing.getInstance().setExpiredLocal(String.valueOf(expiredLocal));
	}

	public boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}

}
